from datetime import datetime
import pygit2
import tempfile
from glob import glob
import os, shutil

VERSION   = pygit2.Repository('.').revparse_single('HEAD').short_id
TIMESTAMP = datetime.now().isoformat()
MAIN      = 'pandoc-zotero-live-citemarkers.lua'
DEPLOYED  = '../site/content/exporting/zotero.lua'
BIB       = os.path.join(os.getcwd(), 'biblio.bib')
AMALG     = shutil.which('amalg.lua')

HEADER = f'''
  print('zotero-live-citations {VERSION}')
  local online, mt, latest = pcall(pandoc.mediabag.fetch, 'https://retorque.re/zotero-better-bibtex/exporting/zotero.lua.revision')
  if online then
    latest = string.sub(latest, 1, 10)
    if '{VERSION}' ~= latest then
      print('new version "' .. latest .. '" available at https://retorque.re/zotero-better-bibtex/exporting')
    end
  end
'''

rule bundle:
  input: glob('*.lua') + ['Snakefile']
  output: DEPLOYED
  run:
    with open(DEPLOYED, 'w') as deployed:
      print(HEADER, file=deployed)
      with tempfile.NamedTemporaryFile(mode='w+') as bundle:
        shell('{AMALG} -o {bundle.name} -s {MAIN} lunajson lunajson.decoder lunajson.encoder lunajson.sax locator utils zotero')
        bundle.seek(0)
        print(bundle.read(), file=deployed)

    with open(DEPLOYED + '.revision', 'w') as deployed:
      deployed.write(VERSION)
    shutil.copy(DEPLOYED, 'bundled.lua')

rule test:
  input: rules.bundle.output
  run:
    shell('rm -f *.docx *.odt *.json')
    shell('pandoc -s --lua-filter={DEPLOYED} -o paper{TIMESTAMP}.odt main.md')
    shell('pandoc -s --lua-filter={DEPLOYED} -o paper{TIMESTAMP}.docx main.md')
    shell('pandoc -s --metadata=zotero_scannable_cite:true --lua-filter={DEPLOYED} -o paper{TIMESTAMP}-scannable-cite.odt main.md')

rule this:
  input: rules.bundle.output
  run:
    shell('pandoc -s --lua-filter=bundled.lua -o 2736.docx 2736.md')

rule using:
  input: rules.bundle.output
  run:
    shutil.copy("../test/fixtures/export/Using zotero.lua .md to .docx to add canonic number after comma without 'p.' #2248.md", "using.md")
    shell('pandoc -s --lua-filter=bundled.lua -o using.odt using.md')

rule rocks:
  run:
    shell("brew install luarocks")
    shell("luarocks install lunajson ")
    shell("luarocks install penlight")
    shell("luarocks install amalg")
    shell("luarocks install lpeg")

rule start:
	shell: "npm start -- --import {BIB}"
